package com.iot.inclinometer.ui;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.iot.inclinometer.R;
import com.iot.inclinometer.dao.IBaseInfoDao;
import com.iot.inclinometer.dao.ICorrectDataInfoDao;
import com.iot.inclinometer.dao.impl.BaseInfoDaoImpl;
import com.iot.inclinometer.dao.impl.CorrectDataInfoDaoImpl;
import com.iot.inclinometer.db.DBHelper;
import com.iot.inclinometer.pojo.BaseInfo;
import com.iot.inclinometer.pojo.QueryDataDTO;
import com.iot.inclinometer.pojo.SendDataDTO;
import com.iot.inclinometer.pojo.UploadDataInfo;
import com.iot.inclinometer.pojo.UploadRes;
import com.iot.inclinometer.util.BeanUtil;
import com.iot.inclinometer.util.Common;
import com.iot.inclinometer.util.ContextApplication;
import com.iot.inclinometer.util.TCPClient;
import com.iot.inclinometer.util.TCPClientReceiver;
import com.iot.inclinometer.util.XUtilsHttp;
import com.iot.inclinometer.util.XutilsCallBack;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Vector;

/**
 * 上传数据库数据到服务器页面
 *
 * @author gisboss
 * @date 2020-07-29
 */
@ContentView(R.layout.uploaddbtoserver_activity)
public class UploadDBToServerUI extends Activity {
    private final static String EMPTY_ITEM = "请选择";
    private final static String TAG = UploadDBToServerUI.class.getSimpleName();
    private TextView titleView;        //显示标题(产品型号)
    /**
     * 新项目
     */
    private ImageView newProBtn;
    private ImageView oldProBtn;
    private ImageView paintBtn;
    private ImageView outputBtn;
    private ImageView configurationBtn;
    private ImageView exitBtn;
    private DBHelper helper;



    // tcp
    private TCPClient tcpClient;
    /**
     * 上传数据的服务器的IP地址
     */
    private EditText upload_ip_edit = null;
    /**
     * 上传数据的服务器的端口
     */
    private EditText upload_port_edit = null;

    /**
     * 项目名称
     */
    private Spinner prjName_Picker = null;
    /**
     * 工点名称
     */
    private Spinner wpName_Picker = null;
    /**
     * 钻孔编号名称，监测点名称
     */
    private Spinner drillName_Picker = null;

    private ArrayAdapter<String> projectAdapter = null;

    private ArrayAdapter<String> wpAdapter = null;

    private ArrayAdapter<String> drillAdapter = null;
    private IBaseInfoDao baseInfoDao = new BaseInfoDaoImpl(this);

    /**
     * 数据过滤起始时间
     */
    private EditText startTime_editText = null;
    /**
     * 数据过滤结束时间
     */
    private EditText endTime_editText = null;


    //时间选择器
    private TimePickerView pvTime;

    /**
     * 显示服务器应答消息
     */
    private TextView server_response_editText = null;

    private TextView queryDataResultTip_editText = null;


    private Button queryDataBtn = null;

    /**
     * 查询条件封装对象列表
     */
    private Vector<QueryDataDTO> queryDataDTOVector;

    /**
     * 开始导出
     */
    @ViewInject(R.id.start_upload_btn)
    private Button startUploadBtn;
    private Button stopUploadBtn = null;
    private CheckBox modifyIpPortBtn = null;

    private final String MEASURE_ANGLE_0 = "A0方向";
    private final String MEASURE_ANGLE_180 = "A180方向";
    private String model;
    private String serverIp;
    private String api;
    private int port;
    private ICorrectDataInfoDao correctDataInfoDao = new CorrectDataInfoDaoImpl(this);

    private Handler mMainHandler;

    List<UploadDataInfo> uploadDataInfoList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        SharedPreferences sharedPreferences = ContextApplication.getAppContext().getSharedPreferences("configuration", 0);
        model = sharedPreferences.getString("Model", "");
        x.view().inject(this);
        helper = new DBHelper(ContextApplication.getAppContext());

        initView();
        setBtnListener();//设置监听

        initMenu();// 绑定工程名称

        // 实例化主线程,用于更新接收过来的消息
        mMainHandler = new MessageHandler(this);

        queryDataDTOVector = new Vector<>();
    }

    @Override
    protected void onDestroy() {
        Log.d(TAG, "page destroied");
        try {
            if (tcpClient != null) {
                tcpClient.getSocketConnManager().unRegisterReceiver(tcpClient.getTcpClientReceiver());
                tcpClient.disconnect();
                tcpClient = null;
            }

            if (mMainHandler != null) {
                mMainHandler.removeCallbacksAndMessages(null);
                mMainHandler = null;
            }

            if (queryDataDTOVector.size() > 0) {
                // 本地先缓存 todo

                // 释放空间
                queryDataDTOVector.clear();
                queryDataDTOVector = null;
            }

            super.onDestroy();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /*
     * 初始化控件
     * */
    private void initView() {
        titleView = (TextView) findViewById(R.id.tv_top_title);    //初始化标题
        String newTitle = Common.isEmpty(model) ? "" : "(" + model + ")";
        titleView.setText(titleView.getText() + newTitle);


        newProBtn = (ImageView) findViewById(R.id.new_pro_btn);
        oldProBtn = (ImageView) findViewById(R.id.old_pro_btn);
        paintBtn = (ImageView) findViewById(R.id.paint_btn);
        outputBtn = (ImageView) findViewById(R.id.output_btn);
        configurationBtn = (ImageView) findViewById(R.id.configuration_btn);
        exitBtn = (ImageView) findViewById(R.id.exit_btn);

        upload_ip_edit = (EditText) findViewById(R.id.upload_ip_edit);
        upload_port_edit = (EditText) findViewById(R.id.upload_port_edit);
        startTime_editText = (EditText) findViewById(R.id.startTime_uploaddb);
        endTime_editText = (EditText) findViewById(R.id.endTime_uploaddb);

        queryDataBtn = (Button) findViewById(R.id.queryData_btn);
        stopUploadBtn = (Button) findViewById(R.id.stop_upload_btn);
        modifyIpPortBtn = (CheckBox) findViewById(R.id.modify_ipport_cb);

        server_response_editText = (TextView) findViewById(R.id.server_response_editText);
        queryDataResultTip_editText = (TextView) findViewById(R.id.queryDataResultTip_uploadData);

        prjName_Picker = (Spinner) findViewById(R.id.prjname_uploaddb);
        wpName_Picker = (Spinner) findViewById(R.id.wpname_uploaddb);
        drillName_Picker = (Spinner) findViewById(R.id.drillname_uploaddb);

        //时间选择器
        pvTime = new TimePickerBuilder(UploadDBToServerUI.this, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
                Log.i(TAG, date.toString());
                ((EditText) v).setText(Common.getTime(date, "yyyy-MM-dd HH:mm"));
            }
        })
                .setType(new boolean[]{true, true, true, true, true, true})
                .setLabel("年", "月", "日", "时", "分", "秒")
                .setCancelText("取消")
                .setSubmitText("确定")
                .build();
    }

    /**
     * 设置所有按钮的点击监听
     */
    private void setBtnListener() {
        // 导航菜单
        newProBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(UploadDBToServerUI.this, NewProUI.class);
                startActivity(intent);
                UploadDBToServerUI.this.finish();
            }
        });

        oldProBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(UploadDBToServerUI.this, OldProUI.class);
                startActivity(intent);
                UploadDBToServerUI.this.finish();
            }
        });
        paintBtn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent(UploadDBToServerUI.this, PaintProUI.class);
                startActivity(intent);
                UploadDBToServerUI.this.finish();
            }
        });
        outputBtn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent(UploadDBToServerUI.this, OutputProUI.class);
                startActivity(intent);
                UploadDBToServerUI.this.finish();
            }
        });
        configurationBtn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent intent = new Intent(UploadDBToServerUI.this, ConfigurationLicenseUI.class);
                startActivity(intent);
            }
        });
        exitBtn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                sureDialog("确定退出程序吗？");
            }
        });


        //=== 开始业务功能 ===//
        prjName_Picker.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view,
                                       int position, long id) {
                try {
                    String selectedProject = prjName_Picker.getSelectedItem().toString();
                    initMenu2(selectedProject);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        wpName_Picker.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parent, View view,
                                       int position, long id) {
                try {
                    String selectedProject = prjName_Picker.getSelectedItem().toString();
                    String selectedItem = wpName_Picker.getSelectedItem().toString();
                    initMenu3(selectedProject, selectedItem);
                } catch (Exception exception) {
                    exception.printStackTrace();
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        drillName_Picker.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> parent, View view,
                                       int position, long id) {

            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        startTime_editText.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {

                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    pvTime.show(v);
                }
                return true;
            }


        });
        endTime_editText.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                // return onDateTimeTouched(v, event, endTime_editText);

                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    pvTime.show(v);
                }
                return true;
            }
        });

        startUploadBtn.setOnClickListener(startUploadBtnClickListener);

        stopUploadBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (tcpClient != null) {
                    String s = "";
                    try {
                        tcpClient.disconnect();
                        stopUploadBtn.setEnabled(false);
                        s = "已断开连接\n";
                        Log.i(TAG, s);

                    } catch (Exception e) {
                        s = String.format("断开连接失败: >> %s \n", e.getLocalizedMessage());
                        Log.e(TAG, s);
                    }

                    startUploadBtn.setEnabled(true);


                    if (null == server_response_editText) {
                        return;
                    }
                    String oldStr = server_response_editText.getText().toString();
                    if (null != oldStr && !oldStr.isEmpty()) {
                        s = new StringBuilder(oldStr).append("\n").append(s).toString();
                    } else {

                    }
                    server_response_editText.setText(s);

                }
            }
        });


        modifyIpPortBtn.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                upload_ip_edit.setEnabled(isChecked);
                upload_port_edit.setEnabled(isChecked);
            }
        });


        queryDataBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // 查询 数据
                String prjName = prjName_Picker.getSelectedItem().toString();
                String wpName = wpName_Picker.getSelectedItem().toString();
                String drillName = drillName_Picker.getSelectedItem().toString();

                String startTime = startTime_editText.getText().toString().trim();
                String endTime = endTime_editText.getText().toString().trim();

                if (Common.isEmpty(prjName) || "请选择".equals(prjName)) {
                    Common.showMsg("请选择工程名称！");
                    startUploadBtn.setEnabled(false);
                    return;
                }

                if (Common.isEmpty(startTime) || Common.isEmpty(endTime)) {
                    Common.showMsg("请选择时间过滤条件！");
                    startUploadBtn.setEnabled(false);
                    return;
                }



                //不过滤 测量方向
                String measureDir = null;// MEASURE_ANGLE_0;

                QueryDataDTO queryDataDTO = new QueryDataDTO(prjName, wpName, drillName, startTime, endTime, measureDir);
                if (hasQueryParamsIntersect(queryDataDTO)) {
                    Common.showMsg("请重新选择查询条件，该条件会有重复提交数据的可能！");
                    startUploadBtn.setEnabled(false);
                    return;
                }

                uploadDataInfoList = readDataFromDB(prjName, wpName, drillName, startTime, endTime, measureDir);

                if (uploadDataInfoList.isEmpty()) {
                    Common.showMsg("没有数据需要上传！");
                    startUploadBtn.setEnabled(false);
                    return;
                }

                // 清除
                if (!queryDataDTOVector.isEmpty()) {
                    queryDataDTOVector.clear();
                }


                queryDataDTO.buildSendDataDTO(uploadDataInfoList);
                queryDataDTOVector.add(queryDataDTO);

                queryDataResultTip_editText.setText(String.format("查询数据%d条", uploadDataInfoList.size()));

                startUploadBtn.setEnabled(true);
            }
        });
    }

    /**
     * 初始化三级联动菜单
     */
    private void initMenu() {
        try {
            initMenu1();
//            initMenu2();
//            initMenu3();
        } catch (Exception e) {

        }
    }

    private void initMenu1() throws Exception {
        // ---------------------初始化项目名称-start---------------------------
        Set<String> projectNameSet = new HashSet<>(); // 保存不重复的项目名
        List<String> projectNames = new ArrayList<>(); // 将Set集合转成List集合,从而放入适配器

        List<BaseInfo> allBaseInfo = this.baseInfoDao.selectBaseInfos();

        for (BaseInfo baseInfo : allBaseInfo) {
            projectNameSet.add(baseInfo.getProjectName());
        }
        for (String projectName : projectNameSet) {
            projectNames.add(projectName);
        }
        Collections.sort(projectNames);//顺序排列

        projectNames.add(0, EMPTY_ITEM);
        // 把数组导入到ArrayList中
        projectAdapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_spinner_item, projectNames);
        projectAdapter
                .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        // 设置下拉菜单的风格
        prjName_Picker.setAdapter(projectAdapter);
        // 绑定适配器
        prjName_Picker.setPrompt("请选择项目名");
    }

    private void initMenu2(String selectedProject) throws Exception {
        // **************************初始化二级联动菜单**start****************************
//        String selectedProject = prjName_Picker.getSelectedItem().toString();
        Set<String> allItemsSet = new HashSet<String>();
        List<String> allItemsList = new ArrayList<String>();
        List<BaseInfo> allItems = this.baseInfoDao
                .selectBaseInfos(selectedProject); // 通过选中的项目名来取得对应的记录，从而得出二级目录的数据
        for (BaseInfo baseInfo : allItems) {
            allItemsSet.add(baseInfo.getItemName());
        }
        for (String item : allItemsSet) {
            allItemsList.add(item);
        }
        Collections.sort(allItemsList);//顺序排列
        allItemsList.add(0, EMPTY_ITEM);
        // 把数组导入到ArrayList中
        wpAdapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_spinner_item, allItemsList);
        wpAdapter
                .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        // 设置下拉菜单的风格
        wpName_Picker.setAdapter(wpAdapter);
        // 绑定适配器
        wpName_Picker.setPrompt("请选择工点名");
        // **************************初始化二级联动菜单**end*************************
    }

    private void initMenu3(String selectedProject, String selectedItem) throws Exception {
//        String selectedProject = prjName_Picker.getSelectedItem().toString();
//        String selectedItem = wpName_Picker.getSelectedItem().toString();
        Set<String> allDrillSet = new HashSet<String>();
        List<String> allDrillList = new ArrayList<String>();

        List<BaseInfo> allDrills = this.baseInfoDao.selectBaseInfos(
                selectedProject, selectedItem);
        for (BaseInfo baseInfo : allDrills) {
            allDrillSet.add(baseInfo.getDrillNum());
        }
        for (String drillNum : allDrillSet) {
            allDrillList.add(drillNum);
        }
        Collections.sort(allDrillList);//顺序排列
        allDrillList.add(0, EMPTY_ITEM);
        drillAdapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_spinner_item, allDrillList);
        drillAdapter
                .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        drillName_Picker.setAdapter(drillAdapter);
        drillName_Picker.setPrompt("请选择钻孔编号");
    }

    private List<UploadDataInfo> getLastData(String prjName, String wpName, String drillNo,String time){
        StringBuilder sql = new StringBuilder();
        List<String> args = new ArrayList<>();
        args.addAll(Arrays.asList(new String[]{prjName, wpName,drillNo,time}));
        sql.append("select a.depth, a.a0, a.b0,a.lx,a.ly,a.error,b.time from correct_data_info a inner join")
            .append("(select ob_id,time from observe_info where base_id=")
            .append("(select base_id from base_info where project_name = ? and item_name = ? and drill_num = ?)")
            .append(" and time < ? order by time desc limit 0,2) b on a.ob_id=b.ob_id");
        List<UploadDataInfo> res= new ArrayList<>();
        SQLiteDatabase database = null;
        try {
            database = helper.getReadableDatabase();
            Cursor cursor = database.rawQuery(sql.toString(),args.toArray(new String[args.size()]));
            while (cursor.moveToNext()) {
                UploadDataInfo uploadDataInfo = new UploadDataInfo();
                uploadDataInfo.setDepth(cursor.getString(cursor.getColumnIndex("depth")));
                uploadDataInfo.setA0(cursor.getString(cursor.getColumnIndex("A0")));
                uploadDataInfo.setB0(cursor.getString(cursor.getColumnIndex("B0")));
                uploadDataInfo.setLx(cursor.getString(cursor.getColumnIndex("lx")));
                uploadDataInfo.setLy(cursor.getString(cursor.getColumnIndex("ly")));
                uploadDataInfo.setError(cursor.getString(cursor.getColumnIndex("error")));
                uploadDataInfo.setTime(cursor.getString(cursor.getColumnIndex("time")));
                res.add(uploadDataInfo);
            }
        } catch (Exception e) {
            Common.showMsg("读取数据库失败!");
            e.printStackTrace();
        } finally {
            if (database != null) {
                database.close();
            }
        }

        return res;
    }
    /**
     * 从数据库读取数据
     *
     * @param prjName
     * @param wpName
     * @param drillNo
     * @param startTime
     * @param endTime
     * @param measureDir
     * @return
     */
    private List<UploadDataInfo> readDataFromDB(String prjName, String wpName, String drillNo, String startTime, String endTime, String measureDir) {
        List<UploadDataInfo> uploadDataInfoList = new ArrayList<>();

        // 存放A0方向测量结果
        StringBuilder sb = new StringBuilder();
        List<String> args = new ArrayList<>(6);
        args.addAll(Arrays.asList(new String[]{startTime, endTime}));
        sb.append("select b.project_name prjname,b.item_name wpname,b.drill_num drillno,c.ob_id,c.data_id,c.depth,c.a0,c.b0,c.lx,c.ly,c.error, o.time, c.a180, c.b180 from ")
                .append("base_info b inner join observe_info o on b.base_id = o.base_id inner join correct_data_info c on o.ob_id = c.ob_id ")
//                .append("where o.measurecount = ? and o.time between datetime('").append(startTime).append("') and datetime('").append(endTime).append("')");
                .append("where (datetime(o.time) >= ? and datetime(o.time) <= ? )");
        if (!Common.isEmpty(prjName) && !EMPTY_ITEM.equals(prjName)) {
            sb.append(" and b.project_name = ?");
            args.add(prjName);
        }
        if (!Common.isEmpty(wpName) && !EMPTY_ITEM.equals(wpName)) {
            sb.append(" and b.item_name = ?");
            args.add(wpName);
        }
        if (!Common.isEmpty(drillNo) && !EMPTY_ITEM.equals(drillNo)) {
            sb.append(" and b.drill_num = ?");
            args.add(drillNo);
        }

        if (!Common.isEmpty(measureDir)) {
            sb.append(" and o.measurecount = ?");
            args.add(measureDir);
        }
        sb.append(" order by o.time asc");


        Log.d(TAG, sb.toString());
        //导出多次观测的修正数据
        SQLiteDatabase database = null;
        try {
            database = helper.getReadableDatabase();
            Cursor cursor = database.rawQuery(sb.toString(), args.toArray(new String[args.size()]));

            while (cursor.moveToNext()) {
                UploadDataInfo uploadDataInfo = new UploadDataInfo();
                uploadDataInfo.setObserverId(cursor.getInt(cursor.getColumnIndex("ob_id")));
                uploadDataInfo.setDataId(cursor.getInt(cursor.getColumnIndex("data_id")));
                uploadDataInfo.setDepth(cursor.getString(cursor.getColumnIndex("depth")));
                uploadDataInfo.setA0(cursor.getString(cursor.getColumnIndex("A0")));
                uploadDataInfo.setB0(cursor.getString(cursor.getColumnIndex("B0")));
                uploadDataInfo.setTime(cursor.getString(cursor.getColumnIndex("time")));
                uploadDataInfo.setProjectName(cursor.getString(cursor.getColumnIndex("prjname")));
                uploadDataInfo.setWorkpointName(cursor.getString(cursor.getColumnIndex("wpname")));
                uploadDataInfo.setDrillNo(cursor.getString(cursor.getColumnIndex("drillno")));
                uploadDataInfo.setA180(cursor.getString(cursor.getColumnIndex("A180")));
                uploadDataInfo.setB180(cursor.getString(cursor.getColumnIndex("B180")));
                uploadDataInfo.setLx(cursor.getString(cursor.getColumnIndex("lx")));
                uploadDataInfo.setLy(cursor.getString(cursor.getColumnIndex("ly")));
                uploadDataInfo.setError(cursor.getString(cursor.getColumnIndex("error")));
                uploadDataInfoList.add(uploadDataInfo);
            }
        } catch (Exception e) {
            Common.showMsg("读取数据库失败!");
            e.printStackTrace();
        } finally {
            if (database != null) {
                database.close();
            }
        }

        return uploadDataInfoList;
    }

    /**
     * 判断是否存在查询 条件 重叠
     *
     * @param newQuery
     * @return
     */
    private boolean hasQueryParamsIntersect(QueryDataDTO newQuery) {
        boolean find = false;
        for (QueryDataDTO item : queryDataDTOVector) {
            if (item.getUploaded() > -1 && item.intersect(newQuery)) {
                find = true;
                break;
            }
        }
        return find;
    }

    /**
     * 查询还没有上传的数据的索引位置
     *
     * @return
     */
    private int getToUploadItem() {
        int index = -1;
        int findIndex = -1;
        for (QueryDataDTO item : queryDataDTOVector) {
            index++;
            if (item.getUploaded() < 0) {
                findIndex = index;
                break;
            }
        }
        return findIndex;
    }

    /**
     * 上传事件监听方法
     */
    private OnClickListener startUploadBtnClickListener = new OnClickListener() {
        @Override
        public void onClick(View v) {

            serverIp = upload_ip_edit.getText().toString().trim();
            port = Integer.parseInt(upload_port_edit.getText().toString().trim());

//            if (Common.isEmpty(serverIp) || port < 1) {
//                Common.showMsg("ip地址或端口号不能为空！");
//                return;
//            }

            int index = getToUploadItem();
//            if (index < 0) {
//                Common.showMsg("当前无待上传数据，请查询数据后再上传！");
//                return;
//            }


            String url = "http://"+serverIp+":"+port+"/app/v1/addRecord";
//            Vector<SendDataDTO> dataList = queryDataDTOVector.get(index).getResultData();
            List<UploadDataInfo>  last = new ArrayList<>();
            last = getLastData(uploadDataInfoList.get(0).getProjectName(),uploadDataInfoList.get(0).getWorkpointName(),uploadDataInfoList.get(0).getDrillNo(),uploadDataInfoList.get(0).getTime());

            Map map = new HashMap();
            UploadRes res = new UploadRes();
            BeanUtil.translate(uploadDataInfoList,res);
            BeanUtil.mathData(res.getDataGroup(),last);
            map.put("res", JSON.toJSONString(res));
            XUtilsHttp.Post(url, map,new XutilsCallBack<String>(){
                @Override
                public void onSuccess(String result) {
                    super.onSuccess(result);
                    Toast.makeText(UploadDBToServerUI.this,result,Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {
                    super.onError(ex, isOnCallback);
                }
            });
//            uploadData(queryDataDTOVector.get(index));
            // socket 通信
//            socketConn(queryDataDTOVector.get(index));

            startUploadBtn.setEnabled(false);

        }
    };


//    public void uploadData(QueryDataDTO queryDataDTO) {
//        final Vector<SendDataDTO> dataList = queryDataDTO.getResultData();
//        server_response_editText.append("开始发送数据\n");
//        SharedPreferences sharedPreferences=ContextApplication.getAppContext().getSharedPreferences("configuration",0);
//        final String api = sharedPreferences.getString("api", null);
//        //开启线程，发送请求
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                HttpURLConnection connection = null;
//                BufferedReader reader = null;
//                try {
//                    URL url = new URL(api);
//                    connection = (HttpURLConnection) url.openConnection();
//                    //加入数据
//                    connection.setRequestMethod("POST");
//                    connection.setRequestProperty("Content-Type","application/json; charset=UTF-8");
//                    connection.setRequestProperty("accept","application/json");
//                    PrintWriter writer = new PrintWriter(connection.getOutputStream());
//                    if (dataList != null) {
//                        Gson res = new Gson();
//                        String s = res.toJson(dataList.get(0));
//                        show("数据条数：" + dataList.get(0).calcCount() );
//                        writer.write(s);
//                    }
//                    writer.flush();
//                    writer.close();
//                    //设置连接超时时间（毫秒）
//                    connection.setConnectTimeout(5000);
//                    //设置读取超时时间（毫秒）
//                    connection.setReadTimeout(5000);
//                    //返回输入流
//                    InputStream in = connection.getInputStream();
//                    //读取输入流
//                    reader = new BufferedReader(new InputStreamReader(in));
//                    StringBuilder result = new StringBuilder();
//                    String line;
//                    while ((line = reader.readLine()) != null) {
//                        result.append(line);
//                    }
//                    show("接口返回结果：" + result.toString());
//                } catch (MalformedURLException e) {
//                    e.printStackTrace();
//                } catch (ProtocolException e) {
//                    e.printStackTrace();
//                } catch (IOException e) {
//                    e.printStackTrace();
//                } finally {
//                    if (reader != null) {
//                        try {
//                            reader.close();
//                        } catch (IOException e) {
//                            e.printStackTrace();
//                        }
//                    }
//                    if (connection != null) {//关闭连接
//                        connection.disconnect();
//                    }
//                }
//            }
//        }).start();
//    }
    /**
     * 展示
     *
     * @param result
     */
    private void show(final String result) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                server_response_editText.append(result + "\n");
            }
        });
    }

    private void socketConn(QueryDataDTO queryDataDTO) {

        Vector<SendDataDTO> dataList = queryDataDTO.getResultData();

        // tcp
        if (tcpClient == null) {

            tcpClient = new TCPClient(serverIp, port, this.mMainHandler);
            tcpClient.open().registerReceiver(new TCPClientReceiver(dataList, tcpClient));

        } else {
            tcpClient.getTcpClientReceiver().setSendDataDTO(dataList);

        }
        server_response_editText.setText("【提示】连接服务器......");
        tcpClient.connect();
//        // udp
//        new UDPClient("10.88.89.76",8280).start();

    }


    /**
     * 确认框
     */
    public void sureDialog(String msg) {
        AlertDialog.Builder builder = new Builder(this);
        builder.setMessage(msg);
        builder.setTitle("提示");
        builder.setPositiveButton("确定",
                new android.content.DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        android.os.Process.killProcess(android.os.Process
                                .myPid());
                    }
                });
        builder.setNegativeButton("取消",
                new android.content.DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
        builder.create().show();
    }


    private static class MessageHandler extends Handler {
        private final String lineSeparator = Common.getLineSep();

        //持有弱引用MainActivity,GC回收时会被回收掉.
        private final WeakReference<UploadDBToServerUI> mainActivity;

        public MessageHandler(UploadDBToServerUI ma) {
            this.mainActivity = new WeakReference<UploadDBToServerUI>(ma);
        }


        @Override
        public void handleMessage(Message msg) {
            if (null == this) {
                Log.d(TAG, "MessageHandler is null");
                return;
            }
            UploadDBToServerUI mainActivity = this.mainActivity.get();
            if (mainActivity == null || mainActivity.isFinishing()) {
                Log.d(TAG, "UploadDBToServerUI is finished");
                return;
            }

            super.handleMessage(msg);
            StringBuilder sb = new StringBuilder();
            TextView msgUI = this.mainActivity.get().server_response_editText;
            if (null == msgUI) {
                return;
            }
            String oldStr = msgUI.getText().toString();
            if (null != oldStr && !oldStr.isEmpty()) {
                sb.append(oldStr).append(lineSeparator);
            }
            switch (msg.what) {
                case 0x9527:// 接收子线程的消息
                    String md = msg.getData().getString(TCPClient.KEY_MSG);
                    if (!Common.isEmpty(md)) {
                        sb.append(md.trim());
                    }
                    break;
                case 0x9528: // 关闭连接
                case 0x9526: // 连接断开或失败
                    this.mainActivity.get().startUploadBtn.setEnabled(true);
                    this.mainActivity.get().stopUploadBtn.setEnabled(false);
                    String msg2 = msg.getData().getString(TCPClient.KEY_MSG);
                    if (!Common.isEmpty(msg2)) {
                        sb.append(msg2.trim());
                    }
                    break;

                case 0x9525: // 连接成功
                    this.mainActivity.get().startUploadBtn.setEnabled(false);
                    this.mainActivity.get().stopUploadBtn.setEnabled(true);

                    String md2 = msg.getData().getString(TCPClient.KEY_MSG);
                    if (!Common.isEmpty(md2)) {
                        sb.append(md2.trim());
                    }

                    break;


                default:
                    sb.append("未知来源的消息");
                    break;
            }

            msgUI.setText(sb.toString());
        }
    }
}

